package cn.lls.base.util;

import cn.lls.base.common.LlsEnum;
import cn.lls.base.exception.LlsException;
import cn.lls.base.result.ResultCode;
import io.jsonwebtoken.*;
import java.util.Date;

/**
 * Token工具类
 * @ClassName TokenUtil
 * @Author 划水艺术家
 * @Date 2022/11/18 16:43
 * @Version 1.0
 **/
public class TokenUtil {

    // 过期时间，设定为 一天 即 24小时 --- 24 * 60 * 60 * 1000
    private static final long tokenExpiration =  24 * 60 * 60 * 1000;
    // 签名秘钥
    private static final String tokenSignKey = "L1L2S3NCBDLZDMSHHH";

    /*
        根据 登录角色Id、身份 生成token
        userId: 登录角色的Id; 登录角色有：超级管理员、单位管理员、公司员工
        identity: 登录角色身份
            identity = sa, 超级管理员
            identity = ca, 单位管理员
            identity = common, 公司员工
     */
    public static String createToken(Long userId, LlsEnum.LlsIdentify llsIdentify) {
        return Jwts.builder()
                .setSubject("LLS-JWT")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("userId", userId)
                .claim("identity", llsIdentify.getIdentify())
                .signWith(SignatureAlgorithm.HS256, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
    }

    // 根据 token 字符串得到用户id
    public static Long getUserId(String token) {
        try{
            JwtParser jwtParser = Jwts.parser().setSigningKey(tokenSignKey);
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            String userId = claims.get("userId").toString();
            return Long.parseLong(userId);
        }catch (ExpiredJwtException e){
            throw new LlsException(ResultCode.TOKEN_EXPIRE, "令牌过期");
        }catch (Exception e){
            throw new LlsException(ResultCode.TOKEN_VOID, "伪造令牌无效");
        }
    }

    // 根据token字符串得到用户身份
    public static String getIdentify(String token) {
        try{
            JwtParser jwtParser = Jwts.parser().setSigningKey(tokenSignKey);
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return (String)claims.get("identity");
        }catch (ExpiredJwtException e){
            throw new LlsException(ResultCode.TOKEN_EXPIRE, "令牌过期");
        }catch (Exception e){
            throw new LlsException(ResultCode.TOKEN_VOID, "伪造令牌无效");
        }
    }

    public static void main(String[] args) {
        String token = TokenUtil.createToken(2147483648L, LlsEnum.LlsIdentify.SUPER_ADMIN);
        System.out.println("token = " + token);
        System.out.println("id = " + TokenUtil.getUserId(token));
        System.out.println("identify = " + TokenUtil.getIdentify(token));
    }



}
